package code.command {

import code.Cookie;
import code.Model;
import code.event.LoginEvent;
import code.remote.service.DependencyInjector;
import code.remote.service.ILoginService;

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import logging.Logger;

import mx.controls.Alert;
import mx.core.Application;

public class LoginCommand implements ICommand {
	
	private static const LOG: Logger = Logger.getLogger("code.command.LoginCommand");
	
	private var isLoginRememberEnabled: Boolean;
	
	public function LoginCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: LoginEvent = _event as LoginEvent;
		LOG.fine("Executing login [event="+event+"].");
		
		const username: String = Model.instance.loginUsername;
		const password: String = Model.instance.loginPassword;
		
		const loginService: ILoginService = DependencyInjector.instance.loginService;
		
		Model.instance.isLoginBlocked = true;
		
		loginService.login(username, password, onLoginResult);
		
	}
	
	private function onLoginResult(fetchedUserId: int): void {
		
		const c: Cookie = Cookie.instance;
		const _isRememberEnabled: Boolean = Model.instance.loginRemember;
		
		if(fetchedUserId == -1) {
			// TODO error message in LoginPanel
			Alert.show("Please check username/password!", "Invalid Login");
			
		} else { // valid login
		
			if(_isRememberEnabled == true) {
				// store data
				c.username = Model.instance.loginUsername;
				c.password = Model.instance.loginPassword;
				c.userId = fetchedUserId;
				c.isRememberEnabled = true;
				c.flush();
				
			// not possible because of LogoutCommand
			// } else if(_isRememberEnabled == false && Cookie.instance.isRememberEnabled == true) {
				
			} else { // remember is+was disabled
				c.username = Model.instance.loginUsername;
				c.flush();
			}
			
			Model.instance.loginPassword = '';
			Model.instance.currentUser = Model.instance.getUserById(fetchedUserId);
			Application.application.currentState = 'stateMain';
		}
		
		Model.instance.isLoginBlocked = false;
	}
}
}